<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const loading = ref(false)
const statusList = ref([])
const activeStatus = ref('all')
const orderList = ref([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dispatchDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const employeeList = ref([])
const currentOrder = ref({})

// 获取状态列表
const getStatusList = async () => {
  try {
    const res = await axios.get('/carRepair/admin/repairOrderManage/status')
    if (res.data.code === 200) {
      statusList.value = res.data.data
    }
  } catch (e) {
    ElMessage.error('获取状态列表失败')
  }
}

// 获取订单列表
const getOrderList = async () => {
  loading.value = true
  try {
    const res = await axios.get('/carRepair/admin/repairOrderManage', {
      params: {
        pageNum: page.value,
        pageSize: pageSize.value,
        orderStatus: activeStatus.value === 'all' ? null : activeStatus.value
      }
    })
    if (res.data.code === 200) {
      orderList.value = res.data.data.records
      total.value = res.data.data.total
    }
  } catch (e) {
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取员工列表
const getEmployeeList = async () => {
  try {
    const res = await axios.get('/carRepair/admin/accountManage/employee', {
      params: {
        pageNum: 1,
        pageSize: 100
      }
    })
    if (res.data.code === 200) {
      employeeList.value = res.data.data.records
    }
  } catch (e) {
    ElMessage.error('获取员工列表失败')
  }
}

// 处理状态选择
const handleStatusSelect = (status) => {
  activeStatus.value = status
  page.value = 1
  getOrderList()
}

// 显示派单对话框
const showDispatchDialog = (row) => {
  currentOrder.value = row
  dispatchDialogVisible.value = true
  getEmployeeList()
}

// 显示详情对话框
const showDetailDialog = (row) => {
  currentOrder.value = row
  detailDialogVisible.value = true
}

// 处理派单
const handleDispatch = async (employee) => {
  try {
    const res = await axios.put('/carRepair/admin/repairOrderManage/dispatch', {
      repairId: currentOrder.value.repairId,
      employeeId: employee.accountId
    })
    if (res.data.code === 200) {
      ElMessage.success('派单成功')
      dispatchDialogVisible.value = false
      getOrderList()
    }
  } catch (e) {
    ElMessage.error('派单失败')
  }
}

// 获取第一张图片
const getFirstImage = (urls) => {
  if (!urls) return ''
  return urls.split(',')[0]
}

// 获取图片列表
const getImageList = (urls) => {
  if (!urls) return []
  return urls.split(',')
}

onMounted(() => {
  getStatusList()
  getOrderList()
})
</script>

<template>
  <div class="repair-order-manage">
    <el-card>
      <!-- 状态选择菜单 -->
      <el-menu mode="horizontal" :default-active="activeStatus" @select="handleStatusSelect">
        <el-menu-item index="all">全部</el-menu-item>
        <el-menu-item v-for="status in statusList" :key="status" :index="status">
          {{ status }}
        </el-menu-item>
      </el-menu>

      <!-- 维修订单表格 -->
      <el-table :data="orderList" style="width: 100%; margin-top: 20px" v-loading="loading">
        <el-table-column label="故障拍照" width="120">
          <template #default="scope">
            <el-image 
              style="width: 80px; height: 80px" 
              :src="getFirstImage(scope.row.problemImgUrls)" 
              :preview-src-list="getImageList(scope.row.problemImgUrls)"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column prop="problemDesc" label="故障描述" />
        <el-table-column prop="accountName" label="账户名称" width="120" />
        <el-table-column prop="brand" label="品牌" width="100" />
        <el-table-column prop="model" label="车型" width="120" />
        <el-table-column prop="plateNumber" label="车牌号" width="120" />
        <el-table-column prop="mileage" label="当前里程数" width="120" />
        <el-table-column prop="budgetAmount" label="维修预算金额" width="120">
          <template #default="scope">¥{{ scope.row.budgetAmount }}</template>
        </el-table-column>
        <el-table-column prop="actualCost" label="实际结算金额" width="120">
          <template #default="scope">¥{{ scope.row.actualCost }}</template>
        </el-table-column>
        <el-table-column prop="createTime" label="故障单创建时间" width="180" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button 
              v-if="scope.row.orderStatus === '已预约'"
              type="primary" 
              size="small" 
              @click="showDispatchDialog(scope.row)"
            >
              派单
            </el-button>
            <el-button 
              v-else
              type="info" 
              size="small" 
              @click="showDetailDialog(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="getOrderList"
          @current-change="getOrderList"
        />
      </div>
    </el-card>

    <!-- 派单对话框 -->
    <el-dialog v-model="dispatchDialogVisible" title="选择员工" width="50%">
      <el-table :data="employeeList" style="width: 100%">
        <el-table-column label="员工头像" width="100">
          <template #default="scope">
            <el-avatar :size="50" :src="scope.row.avatarUrl" />
          </template>
        </el-table-column>
        <el-table-column prop="accountName" label="账户名称" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleDispatch(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="50%">
      <div class="detail-content">
        <p><strong>管理员备注说明：</strong>{{ currentOrder.remark || '暂无' }}</p>
        <p><strong>客户回访记录：</strong>{{ currentOrder.feedback || '暂无' }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.repair-order-manage {
  padding: 0px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.detail-content {
  line-height: 2;
}
</style>